﻿#pragma execution_character_set("utf-8")
#include "qq.h"
#include "ui_qq.h"
QQ::QQ(QWidget *parent)
    : QWidget(parent,Qt::Tool)
    , ui(new Ui::QQ)
    , httpClient(new HttpClient("http://127.0.0.1:10400",this))
    , fileOperator(new FileOperator(this))
    , sQLiteUtil(new SQLiteUtil("./accountData/login.db",this))
{

    ui->setupUi(this);
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setAttribute(Qt::WA_TranslucentBackground);//设置窗口透明
    this->setWindowFlags(windowFlags() | Qt::FramelessWindowHint);//去掉窗口的标题
    this->setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);

    //初始化数据库表
    sQLiteUtil->initLoginDB();
    //设置背景动态
    movie=new QMovie(":/background/imagesRes/login_BG.gif");
    movie->setScaledSize(QSize(540,420));
    ui->movie->setMovie(movie);
    movie->start();
    //设置账号提示框
    accTip=new Tip(this);
    accTip->setText("请你输入账号后再登录");
    accTip->move(ui->mainWidget->pos().x()+95,ui->mainWidget->pos().y()+235);
    accTip->hide();
    //设置密码提示框
    pwdTip=new Tip(this);
    pwdTip->setText("请你输入密码后再登录");
    pwdTip->move(ui->mainWidget->pos().x()+95,ui->mainWidget->pos().y()+279);
    pwdTip->hide();
    //设置下拉框选择账号
    menuWidget=new accountDown(sQLiteUtil,this);
    menuWidget->move(ui->mainWidget->pos().x()+120,ui->mainWidget->pos().y()+250);
    menuWidget->hide();

    createShadow();
    createHeadShadow();

    loadHttpComponentRespond();
    loadBaseComponentRespond();

    //读取最近登录的信息
    getRecentLogin();
}

QQ::~QQ()
{
    delete httpClient;
    delete fileOperator;
    delete sQLiteUtil;
    delete accTip;
    delete pwdTip;
    delete movie;
    delete menuWidget;
    delete ui;
}

//鼠标点击事件
void QQ::mousePressEvent(QMouseEvent* event) {
    tipHide();
    if (event->button() == Qt::LeftButton) {
        menuWidget->hide();
        setStyleShowDown();
        ui->account_LB->setPixmap(accountImgPath);
        setStyleAccWT();
        ui->account_LE->clearFocus();
        ui->pwd_LE->clearFocus();

        isDragging = true;
        lastPos =event->pos(); // 鼠标按下时记录鼠标相对窗体的位置
    }
}

//鼠标移动事件
void QQ::mouseMoveEvent(QMouseEvent* event) {
    if (isDragging&&event->buttons() & Qt::LeftButton) {
        // 移动窗口
        move(event->globalPos() - lastPos);//event->globalPos()记录窗体的原点在整个电脑窗口的位置
    }
}

//鼠标释放事件
void QQ::mouseReleaseEvent(QMouseEvent* event){
    if (event->button() == Qt::LeftButton && isDragging) {
        isDragging = false;
    }
}

void QQ::keyPressEvent(QKeyEvent* event){
    if(event->key()==Qt::Key_Enter||event->key()==Qt::Key_Return)
    {
        ui->login_BT->click();
    }
}

void QQ::timerEvent(QTimerEvent *event){//定时器
    if(event->timerId()==timeID){
        static int num=0;
        num++;
        if(num>3){
            num=0;
            ui->logining_LB->setText("Logining");
        }
        else{
            ui->logining_LB->setText(ui->logining_LB->text().append('.'));
        }
    }
    if(event->timerId()==TipLife){
        static int num=0;
        num++;
        if(num>5){
            num=0;
            tipHide();
        }
    }
}

void QQ::createShadow(){//设置窗口的阴影
    QGraphicsDropShadowEffect *mainShadow = new QGraphicsDropShadowEffect(this);
    mainShadow->setOffset(0,0); // 设置阴影偏移量
    mainShadow->setBlurRadius(13); // 设置阴影模糊半径
    mainShadow->setColor(QColor(130,130,130)); // 设置阴影颜色（RGBA）
    ui->mainWidget->setGraphicsEffect(mainShadow);
}

void QQ::createHeadShadow(){//设置头像的阴影
    QGraphicsDropShadowEffect *imgShadow = new QGraphicsDropShadowEffect(ui->mainWidget);
    imgShadow->setOffset(0,0); // 设置阴影偏移量
    imgShadow->setBlurRadius(27); // 设置阴影模糊半径
    imgShadow->setColor(QColor(128, 163, 255)); // 设置阴影颜色（RGBA）
    ui->headImg_WT->setGraphicsEffect(imgShadow);
}

void QQ::loadHttpComponentRespond(){
    connect(httpClient,&HttpClient::finished,[this](const QUrl &url, const QByteArray &data){
        QString URL=url.toString();
        if(URL.contains("login"))
        {
            killTimer(timeID);
            QVariantMap returnMap=fileOperator->parseJsonObject(data);//解析服务器的json
            int status=returnMap["status"].toInt();
            if(status==0){//用户不存在
                ui->login_SWT->setCurrentIndex(0);
            }
            else if(status==1){//密码错误
                ui->main_SWT->setCurrentIndex(1);
            }
            else//登录成功
            {
                returnMap.remove("status");
                QString wsAdrr=returnMap["serverAddr"].toString();//告诉客户端连接哪一台Netty服务器
                returnMap.remove("serverAddr");
                QString token=returnMap["token"].toString();
                returnMap.remove("token");
                if(!returnMap.isEmpty()){//需要更新信息
                    setRecentLogin(returnMap);
                    emit login(wsAdrr,ui->account_LE->text(),returnMap["userName"].toString(),true,returnMap["sign"].toString(),token);
                }
                else//不需要更新信息
                {
                    setRecentLogin(returnMap);
                    QVariantMap resultMap=sQLiteUtil->selectOneLoginUserInfo(ui->account_LE->text());
                    emit login(wsAdrr,ui->account_LE->text(),resultMap["userName"].toString(),false,resultMap["sign"].toString(),token);
                }
            }
        }
    });

    //服务器连接失败后,处理错误信息(包括服务器连接失败,自己取消连接)
    connect(httpClient,&HttpClient::errorOccurred,[this](const QUrl &url,const QNetworkReply::NetworkError &error){
        killTimer(timeID);
        ui->login_SWT->setCurrentIndex(0);
    });
}

void QQ::loadBaseComponentRespond(){
    //关闭窗口
    connect(ui->close_Button, &QPushButton::clicked, [this]() {
        this->close();
        emit quit();
    });

    //最小化窗口
    connect(ui->minimize_Button,&QPushButton::clicked,[this](){
        tipHide();
        this->hide();
    });

    //处理showDown按钮点击事件
    connect(ui->showDown,&QPushButton::clicked,[this](){
        tipHide();
        if (menuWidget->isVisible()) {//激活下拉菜单
            menuWidget->hide();
            setStyleShowDown();
        }
        else{//没激活下拉菜单
            menuWidget->show();
            setStyleShowDown_active();
            ui->account_LB->setPixmap(QPixmap(accountImgPath_active));
            setStyleAccWT_active();
        }
    });

    //跳转链接
    connect(ui->register_BT,&QPushButton::clicked,[this](){
        tipHide();
        QUrl url("http://127.0.0.1:10400/Register");
        QDesktopServices::openUrl(url);// 使用QDesktopServices打开URL
    });

    //跳转到logining页面
    connect(ui->login_BT,&QPushButton::clicked,[this](){
        if (checkLineEdit(ui->account_LE)) {//检查account_LE的text是否为空
            if (checkLineEdit(ui->pwd_LE)) {//检查pwd_LE的text是否为空
                ui->logining_LB->setText("Logining");
                timeID = startTimer(600);
                ui->login_SWT->setCurrentIndex(1);

                QJsonObject rootObject;
                {
                    QJsonObject accountObject;
                    accountObject["email"] = ui->account_LE->text();
                    accountObject["password"] = ui->pwd_LE->text();
                    if(sQLiteUtil->selectOneLoginIsExist(ui->account_LE->text())){
                        QVariantMap resultMap=sQLiteUtil->selectOneLoginAlterTime(ui->account_LE->text());
                        accountObject["alterTime"]=resultMap["alterTime"].toString();
                    }
                    rootObject["account"] = accountObject;
                }
                {
                    QJsonObject deviceInfoObject;
                    if (checkDevice()) {
                        deviceInfoObject["deviceType"]="phone";
                    } else {
                        deviceInfoObject["deviceType"]="computer";
                    }
                    deviceInfoObject["osVersion"]=QSysInfo::productType()+QSysInfo::productVersion();
                    rootObject["deviceInfo"] = deviceInfoObject;
                }

                QJsonDocument jsonDoc(rootObject);
                loginReply=httpClient->post("/App/login",jsonDoc.toJson());//发送http的POST请求
            }
            else {
                if(!pwdTip->isVisible()){//防止按钮在1秒内重复按
                    pwdTip->show();
                    TipLife= startTimer(1000);
                    isTimerRunning=true;
                }
            }
        }
        else {
            if(!accTip->isVisible()){
                accTip->show();
                TipLife= startTimer(1000);
                isTimerRunning=true;
            }
        }
    });

    connect(ui->sure_BT,&QPushButton::clicked,[this](){
        ui->main_SWT->setCurrentIndex(0);
        ui->login_SWT->setCurrentIndex(0);
    });

    //跳转到login页面
    connect(ui->cancel_BT,&QPushButton::clicked,[this](){
        if(loginReply->isRunning()){
            loginReply->abort();
            loginReply->deleteLater();
            loginReply=nullptr;
        }
        ui->pwd_LE->setText("");
        ui->pwd_LE->setFocus();
    });

    //处理account_LE是否聚焦(focus)
    void (AccFocus::*accfocusSigned)(bool hasFocus)=&AccFocus::focusChanged;
    connect(ui->account_LE,accfocusSigned,[this](bool hasFocus){
        tipHide();
        if(hasFocus){//focus
            ui->account_LB->setPixmap(QPixmap(accountImgPath_active));
            setStyleAccWT_active();
        }
        else{//lose focus
            ui->account_LB->setPixmap(QPixmap(accountImgPath));
            setStyleAccWT();
        }
    });

    //处理password_LE是否聚焦(focus)
    void (PwdFocus::*pwdfocusSigned)(bool hasFocus)=&PwdFocus::focusChanged;
    connect(ui->pwd_LE,pwdfocusSigned,[this](bool hasFocus){
        tipHide();
        if(hasFocus){//focus
            ui->account_LB->setPixmap(QPixmap(accountImgPath));
            setStyleAccWT();
            ui->pwd_LB->setPixmap(QPixmap(pwdImgPath_active));
            setStylePwdWT_active();
        }
        else{//lose focus
            ui->pwd_LB->setPixmap(QPixmap(pwdImgPath));
            setStylePwdWT();
        }
    });

    connect(menuWidget,&accountDown::sendUserInfo,[this](QString email){
        ui->account_LE->setText(email);
        QVariantMap map=this->sQLiteUtil->selectOneLoginInfo(email);
        drawHeadImg(ui->headImg_LB,map["headImgUrl"].toString());
        ui->pwd_LE->setText(map["password"].toString());
        if(map["isRemember"].toBool()){
            ui->remebPwd_CB->setChecked(true);
            if(map["isAuto"].toBool())
                ui->autoLogin_CB->setChecked(true);
            else
                ui->autoLogin_CB->setChecked(false);
        }
        else
            ui->remebPwd_CB->setChecked(false);
        menuWidget->hide();
        setStyleShowDown();
    });

    connect(ui->autoLogin_CB,&CheckBox::stateChanged,[this](int status){
        if(status==2)
            ui->remebPwd_CB->setChecked(true);
    });

    connect(ui->remebPwd_CB,&CheckBox::stateChanged,[this](int status){
        if(status==0)
            ui->autoLogin_CB->setChecked(false);
    });
}

//隐藏Tip
void QQ::tipHide(){
    if (accTip->isVisible()) {
        accTip->hide();
    }
    if(pwdTip->isVisible()){
        pwdTip->hide();
    }
    if(isTimerRunning){//只有Tip的窗口出现时
        killTimer(TipLife);
        isTimerRunning=false;
    }
}

//画出头像
void QQ::drawHeadImg(QLabel *label,QString imgRes){
    if(QFile::exists(imgRes)){
        label->setStyleSheet(QString("\
            #headImg_LB {\
                border-radius: 40px;\
                border-image: url('%1') 0 0 0 0 stretch stretch;\
        }\
        ").arg(imgRes));
    }
}


bool QQ::checkLineEdit(QLineEdit* LEdit) {
    QString text= LEdit->text();
    if (text.isEmpty()) {
        return false;
    }
    return true;
}
bool QQ::checkDevice(){
    QScreen *screen = QGuiApplication::primaryScreen();
    QRect screenGeometry = screen->geometry();
    int screenWidth = screenGeometry.width();
    int screenHeight = screenGeometry.height();
    if (screenWidth < 800 || screenHeight < 600) {//手机
        return false;
    } else {//电脑
        return true;
    }
}

void QQ::setRecentLogin(QVariantMap& map){
    if(sQLiteUtil->selectOneLoginIsExist(ui->account_LE->text())){//有就更新
        if(ui->remebPwd_CB->isChecked())
        {
            map["password"]=ui->pwd_LE->text();
            map["isRemember"]=1;
        }
        else
        {
            map["password"]="";
            map["isRemember"]=0;
        }
        if(ui->autoLogin_CB->isChecked())
        {
            map["isAuto"]=1;
        }
        else
        {
            map["isAuto"]=0;
        }
        map["loginTime"]=QDateTime::currentMSecsSinceEpoch();
        sQLiteUtil->updateLoginBind(map,ui->account_LE->text());
    }
    else{//没有就插入
        map["email"]=ui->account_LE->text();
        if(ui->remebPwd_CB->isChecked())
        {
            map["password"]=ui->pwd_LE->text();
            map["isRemember"]=1;
        }
        else
        {
            map["password"]="";
            map["isRemember"]=0;
        }
        if(ui->autoLogin_CB->isChecked())
        {
            map["isAuto"]=1;
        }
        else
        {
            map["isAuto"]=0;
        }
        map["headImgUrl"]=QString("./accountData/%1/headImg/head.png").arg(ui->account_LE->text());
        map["loginTime"]=QDateTime::currentMSecsSinceEpoch();
        sQLiteUtil->insertLogin(map);
    }
}
void QQ::getRecentLogin(){
    QVariantMap map=sQLiteUtil->selectOneLoginRecentInfo();
    if(!map.empty()){
        ui->account_LE->setText(map["email"].toString());
        if(ui->account_LB->text().isEmpty())
        {
            if(map["isRemember"].toBool()){
                ui->remebPwd_CB->setChecked(true);
            }
            ui->pwd_LE->setText(map["password"].toString());
            drawHeadImg(ui->headImg_LB,map["headImgUrl"].toString());
            if(map["isAuto"].toBool())
            {
                ui->autoLogin_CB->setChecked(true);
                ui->login_BT->clicked();
            }
        }
    }
}

void QQ::setStyleShowDown(){
    ui->showDown->setStyleSheet(R"(
#showDown{
    border:none;
    background-image:url(':/background/imagesRes/arrow.png');
    background-repeat:no-repeat;
    background-position:center center;
}
#showDown:hover{
    background-image:url(':/background/imagesRes/arrow_hover.png');
}
    )");
}
void QQ::setStyleShowDown_active(){
    ui->showDown->setStyleSheet(R"(
#showDown{
    border:none;
    background-image:url(':/background/imagesRes/arrow_active.png');
    background-repeat:no-repeat;
    background-position:center center;
}
    )");
}

void QQ::setStyleAccWT(){
    ui->account_WT->setStyleSheet(R"(
#account_WT{
    border-bottom:1px solid rgb(193, 193, 193);
}
#account_WT:hover{
    border-color:rgb(170, 170, 170);
}
    )");
}

void QQ::setStyleAccWT_active(){
    ui->account_WT->setStyleSheet(R"(
#account_WT{
    border-bottom:1px solid rgb(18, 183, 245);
}
    )");
}

void QQ::setStylePwdWT(){
    ui->pwd_WT->setStyleSheet(R"(
#pwd_WT{
    border-bottom:1px solid rgb(193, 193, 193);
}
#pwd_WT:hover{
    border-color:rgb(170, 170, 170);
}
    )");
}

void QQ::setStylePwdWT_active(){
    ui->pwd_WT->setStyleSheet(R"(
#pwd_WT{
    border-bottom:1px solid rgb(18, 183, 245);
}
    )");
}
